package eteam.aps.controller;

import eteam.aps.common.R;
import eteam.aps.common.component.LoginUserRedisService;
import eteam.aps.common.entity.ParentEntity;
import eteam.aps.common.exceptions.AuthException;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.helper.Helper;
import eteam.aps.common.helper.JsonPage;
import eteam.aps.model.dto.ProtectionOrgDto;
import eteam.aps.model.entity.ProtectionOrg;
import eteam.aps.model.entity.ProtectionOrgDtl;
import eteam.aps.model.vo.ProtectionOrgListVo;
import eteam.aps.model.vo.ProtectionOrgVo;
import eteam.aps.model.vo.ProtectionVo;
import eteam.aps.service.ProtectionOrgDtlService;
import eteam.aps.service.ProtectionOrgService;
import eteam.aps.service.QueryInfoService;
import eteam.aps.systeminterface.model.dto.VerifyTokenDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 保障机构控制层
 *
 * @author WMT
 */
@Api(tags = "保障机构模块")
@RestController
public class ProtectionOrgController implements IProtectionOrgController {

    @Autowired
    private ProtectionOrgService protectionOrgService;

    @Autowired
    private ProtectionOrgDtlService protectionOrgDtlService;

    @Autowired
    private QueryInfoService queryInfoService;

    @Autowired
    private LoginUserRedisService loginUserRedisService;

    @Override
    @ApiOperation("新增保障机构")
    @PostMapping("po/insert")
    public R<Integer> insert(@RequestBody ProtectionOrgDto protectionOrgDto) throws Exception, AuthException {
        // 设置用户、部门信息
        VerifyTokenDto user = loginUserRedisService.getUser();
        LocalDateTime now = LocalDateTime.now();
        protectionOrgDto.setfCreateUserId(user.getFuserid());
        protectionOrgDto.setfCreatorTime(now);
        protectionOrgDto.setfLastModifyUserId(user.getFuserid());
        protectionOrgDto.setfLastModifyTime(now);
        protectionOrgDto.setfBookCode(user.getFgrouporgid());
        protectionOrgDto.setfId(Helper.GetId());
        protectionOrgDto.setfState(ParentEntity.FSTATE_DRAFT);

        if (Helper.isEmpty(protectionOrgDto.getfOrgCode()) || Helper.isEmpty(protectionOrgDto.getfOrgName())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"保障机构编号或机构名称不能为空");
        }
        if (Helper.isEmpty(protectionOrgDto.getfRegAddress())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"注册地址不能为空");
        }
        if (Helper.isEmpty(protectionOrgDto.getfContact())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"联系人不能为空");
        }
        if (Helper.isEmpty(protectionOrgDto.getfPhone())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"联系电话不能为空");
        }
        if (protectionOrgService.selectCountByCode(protectionOrgDto.getfOrgCode()) > 0){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"保障机构编号已存在");
        }
        if (protectionOrgService.selectCountByName(protectionOrgDto.getfOrgName()) > 0){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"保障机构名称已存在");
        }

        // 添加保障机构子表数据
        List<ProtectionOrgDtl> orgDtls = protectionOrgDto.getOrgDtls();
        if (orgDtls != null){
            StringBuilder paramInfo = new StringBuilder();
            for (ProtectionOrgDtl protectionOrgDtl : orgDtls) {

                if (Helper.isEmpty(protectionOrgDtl.getfServiceUnitCode()) || Helper.isEmpty(protectionOrgDtl.getfServiceUnitName())){
                    throw new BusinessException(HttpStatus.BAD_REQUEST,"服务单位编号或名称不能为空");
                }

                paramInfo.append(setParamInfo(protectionOrgDtl.getfServiceUnitName(), protectionOrgDtl.getfServiceUnitCode()));
                protectionOrgDto.setfParamInfo(paramInfo.toString());

                protectionOrgDtl.setfId(Helper.GetId());
                protectionOrgDtl.setfDtlId(protectionOrgDto.getfId());
                protectionOrgDtl.setfState(ParentEntity.FSTATE_DRAFT);
                protectionOrgDtl.setfCreateUserId(user.getFuserid());
                protectionOrgDtl.setfCreatorTime(now);
                protectionOrgDtl.setfLastModifyUserId(user.getFuserid());
                protectionOrgDtl.setfLastModifyTime(now);
                protectionOrgDtl.setfBookCode(user.getFgrouporgid());

                List<ProtectionOrgDtl> protectionOrgDtls = new ArrayList<>();
                protectionOrgDtls.add(protectionOrgDtl);
                protectionOrgDtlService.insert(protectionOrgDtls);
            }
        }
        return R.success(protectionOrgService.insert(protectionOrgDto));
    }

    @Override
    @ApiOperation("删除保障机构")
    @PostMapping("po/delete/{fId}")
    public R<Integer> delete(@PathVariable String fId) throws Exception, AuthException {

        if (Helper.isEmpty(fId)){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"机构fId不能为空");
        }
        ProtectionOrg orgDb = protectionOrgService.selectByFId(fId);
        if (orgDb == null){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"机构fId不存在");
        }
        if (protectionOrgService.selectFStateByFId(fId) == ParentEntity.FSTATE_DELETED){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"保障机构已被删除");
        }

        // 删除对应的子表数据
        protectionOrgDtlService.deleteByFDtlId(fId);
        return R.success(protectionOrgService.delete(fId));
    }

    @Override
    @ApiOperation(("修改保障机构信息"))
    @PostMapping("po/update")
    public R<Integer> update(@RequestBody ProtectionOrgDto protectionOrgDto) throws Exception, AuthException {
        // 设置修改人信息、修改时间
        VerifyTokenDto user = loginUserRedisService.getUser();
        protectionOrgDto.setfLastModifyUserId(user.getFuserid());
        LocalDateTime now = LocalDateTime.now();
        protectionOrgDto.setfLastModifyTime(now);

        if (Helper.isEmpty(protectionOrgDto.getfId())) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "机构fId不能为空");
        }
        ProtectionOrg orgDb = protectionOrgService.selectByFId(protectionOrgDto.getfId());
        if (orgDb == null){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "保障机构不存在");
        }
        if (Helper.isEmpty(protectionOrgDto.getfOrgCode()) || Helper.isEmpty(protectionOrgDto.getfOrgName())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"保障机构编号或机构名称不能为空");
        }
        if (Helper.isEmpty(protectionOrgDto.getfRegAddress())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"注册地址不能为空");
        }
        if (Helper.isEmpty(protectionOrgDto.getfContact())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"联系人不能为空");
        }
        if (Helper.isEmpty(protectionOrgDto.getfPhone())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"联系电话不能为空");
        }


        if (!orgDb.getfOrgCode().equals(protectionOrgDto.getfOrgCode())){
            if (protectionOrgService.selectCountByCode(protectionOrgDto.getfOrgCode()) > 0){
                throw new BusinessException(HttpStatus.BAD_REQUEST,"保障机构编号已存在");
            }
        }
        if (!orgDb.getfOrgName().equals(protectionOrgDto.getfOrgName())){
            if (protectionOrgService.selectCountByName(protectionOrgDto.getfOrgName()) > 0){
                throw new BusinessException(HttpStatus.BAD_REQUEST,"保障机构名称已存在");
            }
        }

        List<ProtectionOrgDtl> list = protectionOrgDto.getOrgDtls();
        if (list != null){
            for (ProtectionOrgDtl orgDtl : list) {
                orgDtl.setfLastModifyUserId(user.getFuserid());
                orgDtl.setfLastModifyTime(now);
                protectionOrgDtlService.update(orgDtl);

                Map<String,Object> map = new HashMap<>(2);
                map.put("fDtlId",orgDtl.getfDtlId());
                map.put("fServiceUnitCode",orgDtl.getfServiceUnitCode());
                if (!(protectionOrgDtlService.countCodeByFDtlId(map) > 0)){
                    orgDtl.setfId(Helper.GetId());
                    orgDtl.setfDtlId(protectionOrgDto.getfId());
                    orgDtl.setfState(ParentEntity.FSTATE_DRAFT);
                    orgDtl.setfCreateUserId(user.getFuserid());
                    orgDtl.setfCreatorTime(now);
                    orgDtl.setfLastModifyUserId(user.getFuserid());
                    orgDtl.setfLastModifyTime(now);
                    orgDtl.setfBookCode(user.getFgrouporgid());

                    List<ProtectionOrgDtl> protectionOrgDtls = new ArrayList<>();
                    protectionOrgDtls.add(orgDtl);
                    protectionOrgDtlService.insert(protectionOrgDtls);
                }
            }
        }
        return R.success(protectionOrgService.update(protectionOrgDto));
    }

    @Override
    @ApiOperation("分页查询保障机构")
    @PostMapping("/po/selectAll")
    public R<JsonPage<ProtectionOrgListVo>> selectAll(
            @RequestParam("fOrgCategory") int fOrgCategory,
            @RequestParam(value = "fOrgCode",required = false) String fOrgCode,
            @RequestParam(value = "fOrgName",required = false) String fOrgName,
            @RequestParam("page") int page,
            @RequestParam("pageSize") int pageSize
    ) throws Exception, AuthException {
        Map<String,Object> map = new HashMap<>(4);
        map.put("fOrgCategory",fOrgCategory);
        if (Helper.isNotEmpty(fOrgCode)){
            map.put("fOrgCode",Helper.likeSql(fOrgCode));
        }
        if (Helper.isNotEmpty(fOrgName)){
            map.put("fOrgName",Helper.likeSql(fOrgName));
        }
        JsonPage<ProtectionOrgListVo> jsonPage = protectionOrgService.selectAll(map, Helper.valuePositive(page, 1),
                Helper.valuePositive(pageSize, 10));
        List<ProtectionOrgListVo> list = jsonPage.getList();
        for (ProtectionOrgListVo listVo : list) {
            listVo.setfCredentialName(queryInfoService.selectDdName().get(listVo.getfCredential()));
        }
        return R.success(jsonPage);
    }

    @Override
    @ApiOperation("查询保障机构详情")
    @PostMapping("po/selectDetails/{fId}")
    public R<List<ProtectionOrgVo>> selectDetails(@PathVariable String fId) throws Exception, AuthException {
        if (Helper.isEmpty(fId)){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"机构fId不能为空");
        }
        ProtectionOrg orgDb = protectionOrgService.selectByFId(fId);
        if (orgDb == null){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"机构fId不存在");
        }
        List<ProtectionOrgVo> protectionOrgVos = protectionOrgService.selectDetails(fId);
        for (ProtectionOrgVo vo : protectionOrgVos) {
            vo.setfCredentialName(queryInfoService.selectDdName().get(vo.getfCredential()));
        }
        return R.success(protectionOrgVos);
    }

    @Override
    @ApiOperation("查询保障机构列表")
    @PostMapping("/po/proorglist")
    public R<List<ProtectionVo>> selectProOrgList() throws Exception, AuthException {
        return R.success(protectionOrgService.selectProOrgList());
    }

    private String setParamInfo(String name,String code) {
        StringBuffer paramInfo = new StringBuffer().append(name).append(code).append(";");
        return paramInfo.toString();
    }
}
